package cn.softeem.tushu.service.Impl;

import cn.softeem.tushu.Dao.CartitemDao;
import cn.softeem.tushu.Dao.Impl.CartitemDaoImpl;
import cn.softeem.tushu.Dao.Impl.MainDaoImpl;
import cn.softeem.tushu.Dao.MainDao;
import cn.softeem.tushu.po.Cartitem;
import cn.softeem.tushu.service.CartitemService;
import cn.softeem.tushu.utils.DruidPool;

import java.sql.SQLException;
import java.util.List;

public class CartitemServiceImpl implements CartitemService {
    CartitemDao cartitemDao =new CartitemDaoImpl();
    @Override
    public List<Cartitem> myCart(String uid) {
        try {
            return cartitemDao.myCart(uid);
        } catch (SQLException throwables) {
            throw  new RuntimeException("查询分类失败");
        }
    }

    @Override
    public void addCart(Cartitem cartitem) {
        try {
            DruidPool.beginTransaction();
            Cartitem c = cartitemDao.findByUserAndBook(cartitem.getUser().getUid(), cartitem.getBook().getBid());
            if (c==null){
                cartitemDao.addCart(cartitem);
            }else {
                int quantity=c.getQuantity()+cartitem.getQuantity();
                cartitemDao.updateQuantity(c.getCartItemId(),quantity);
            }
            DruidPool.commitTransaction();
        } catch (SQLException e) {
            try {
                DruidPool.rollTransaction();
            } catch (SQLException e1) {
                throw new RuntimeException(e1);
            }
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateQuantity(String cartItemId, int quantity) {
        try {
            DruidPool.beginTransaction();
            cartitemDao.updateQuantity(cartItemId,quantity);
            DruidPool.commitTransaction();
        } catch (SQLException e) {
            try {
                DruidPool.rollTransaction();
            } catch (SQLException e1) {
                throw new RuntimeException(e1);
            }
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(String cartitemIds) {
        try {
            DruidPool.beginTransaction();
            cartitemDao.delete(cartitemIds);
            DruidPool.commitTransaction();
        } catch (SQLException e) {
            try {
                DruidPool.rollTransaction();
            } catch (SQLException e1) {
                throw new RuntimeException(e1);
            }
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Cartitem> loadCartItems(String cartItemIds) {
        try {
            return cartitemDao.loadCartItems(cartItemIds);
        } catch (SQLException throwables) {
            throw  new RuntimeException("查询分类失败");
        }
    }

}
